<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!-- 列表展示
      el-table -- elementUi提供的表格组件
        :data="employees"               -- 绑定列表数据
        highlight-current-row             -- 当前行高亮
        v-loading="listLoading"           -- 忙等框=加载框
        @selection-change="selsChange"    -- 选项改变会触发
        style="width: 100%;"              -- 占屏幕宽度
      el-table-column -- 表格的列
        type="selection"  --  选项
        type="index"      --  编号
        width="55"        --  当前列的宽度
        prop="name"       --  显示属性的值：属性值必须与后端json数据中的对象的key值一致
        label="姓名"      -- 标签
        sortable          -- 可排序
     -->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工姓名" width="100">
			</el-table-column>
			<el-table-column prop="phone" label="手机号" width="140">
			</el-table-column>
      <el-table-column prop="email" label="邮箱" width="200">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80">
      </el-table-column>
			<el-table-column prop="state" label="状态" width="80" sortable>
        <!-- 自定义模板：通过scope可以获取到当前行对象：scope.row -->
        <template scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">启用</span>
          <span v-else-if="scope.row.state == 0" style="color: red">禁用</span>
        </template>
			</el-table-column>
			<el-table-column prop="department.name" label="所属部门" width="120" sortable>
			</el-table-column>
      <el-table-column prop="shop_id" label="员工类型" width="120" sortable>
        <!-- 自定义模板：通过scope可以获取到当前行对象：scope.row -->
        <template scope="scope">
          <span style="color: green" v-if="scope.row.shop_id">店铺管理员</span>
          <span style="color: red" v-else>系统管理员</span>
        </template>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
          <!-- elmentUi提供的按钮：size表示大小，type表示按钮颜色
           scope.$index：当前行下标
           scope.row：当前行对象
           -->
					<el-button size="small" @click="handlesave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
        el-pagination -- 显示分页栏
          layout="prev, pager, next"                -- 布局【上一页，当前页，下一页】
          @current-change="handleCurrentChange"     -- 点击某一页的时候会处罚
          :page-size="queryParams.pageSize"         -- 绑定每页显示的条数
          :total="pageParams.totals"                -- 绑定总条数
          :current-page="queryParams.currentPage"   -- 绑定当前页
          style="float:right;"                      -- 显示在右边
      -->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage"
                     style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增和修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
				</el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="saveForm.department_id" placeholder="请选择" clearable>
            <el-option v-for="item in departments"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <!-- 员工可以选择多个角色：他们是多对多关系 - 所以有中间表 -->
          <!-- 这里我们设计的是一个员工选一个角色 -->
          <el-select v-model="saveForm.roleId" value-key="id" placeholder="请选择">
            <el-option v-for="item in roles"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

  </section>
</template>

<script>
	export default {
		data() {
			return {
			  // 1. 分页查询
        employees: [],
        totals: 0,
        pageSize: 10,
        currentPage:1,
        listLoading: false,

        // 2. 高级查询
        keyword: '',

        // 3. 批量删除使用
        sels: [], // 列表选中列

        // 4.
				saveFormVisible: false, // 编辑界面是否显示
				saveLoading: false,
        title: '',
				saveFormRules: {
          username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},

				// 编辑界面数据
				saveForm: {
					id: null,
          username: '',
          phone: '',
          email: '',
          salt: '',
          password: '123456',
          age: null,
          state: 1,
          department_id: null,
          //为员工添加或修改角色
          roleId:null,
          logininfo_id: null,
          shop_id: null
				},

        // 员工所属部门
        departments: [],

        roles:[], // 显示所有的角色 - 方便员工选择角色
			}
		},
		methods: {
      // 1.获取部门列表
      getEmployees() {
        let paras = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword: this.keyword
        };
        this.listLoading = true;
        this.$http.post("/employee", paras).then(result => {
          this.employees = result.data.data;
          this.totals = result.data.totals;
          this.listLoading = false;
        }).catch(result => {
          this.$message.error("系统繁忙，请稍后重试!!!");
        })
      },

      // 2. 分页查询
      handleCurrentChange(val) {
        this.currentPage  = val;
        this.getEmployees();
      },

      // 3. 高级查询
      keywordQuery() {
        this.currentPage = 1;
        this.getEmployees();
      },

      // 4. 删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/employee/" + row.id).then(result=>{
            if (result.data.success) {
              let totalPage = Math.ceil(this.totals/this.pageSize)
              if ((this.totals-1)%this.pageSize == 0 && this.currentPage != 1) {
                this.currentPage = this.currentPage -1;
              }
              this.getEmployees();
            } else {
              this.$message.error("系统繁忙，请稍后重试！！！【500】");
            }
          }).catch(result=>{
            this.$message.error("系统繁忙，请稍后重试！！！【404】");
          })
        }).catch(() => {

        });
      },

      // 5. 赋值
      selsChange: function (sels) {
        this.sels = sels;
      },

      // 6. 批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
         this.$http.patch("/employee", ids).then(result=>{
           if (result.data.success) {
             this.currentPage = 1;
             this.getEmployees();
           } else {
             this.$message.error("系统繁忙，请稍后重试！！！【500】");
           }
           this.listLoading = false;
         }).catch(result=>{
           this.$message.error("系统繁忙，请稍后重试！！！【404】");
         })
        }).catch(() => {
        });
      },

			// 点击编辑弹出对话框
			handlesave: function (index, row) {
        this.title = "编辑",
        // 将row的数据给到空的{},这样不会影响到其他数据使用
				this.saveForm = Object.assign({}, row);
        this.getRoles();
        this.getDepartments();
        this.saveFormVisible = true;
			},

			// 显示新增弹出对话框
			handleAdd: function () {
        this.title = "添加",
				this.saveForm = {
          id: null,
          username: '',
          phone: '',
          email: '',
          salt: '',
          password: '',
          age: null,
          state: 1,
          department_id: null,
          logininfo_id: null,
          shop_id: null
				};
        //加载部门树
        this.getRoles();
        this.getDepartments();
        this.saveFormVisible = true;
			},

			// 新增和修改提交
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
              let paras = Object.assign({}, this.saveForm);
							this.$http.put("/employee", this.saveForm).then(result=>{
							  if (result.data.success) {
							    this.getEmployees();
                } else {
                  this.$message.error("系统繁忙，请稍后重试！！！【500】");
                }
							  this.saveLoading = false
              }).catch(result=>{
                this.$message.error("系统繁忙，请稍后重试！！！【404】");
                this.saveLoading = false
              })
              this.saveFormVisible = false;
						});
					}
				});
			},
      getDepartments() {
        this.$http.get("/department").then(result=>{
          this.departments = result.data;
        })
      },
      getRoles(){
        this.$http.get("/role").then(res=> {
          this.roles = res.data;
        })
      }
		},
		mounted() {
			this.getEmployees();
		}
	}
</script>

<style></style>